package utils;

import apidocs.ApiService;
import apidocs.ApiUser;
import controllers.ApiDoc;
import org.apache.commons.lang.StringUtils;
import play.mvc.Scope;

import java.util.*;

/**
 * @author zhangzc
 * @since 2017/7/18
 */
public class ApiUtil {

    public static boolean hasPermission(Class clazz){
        ApiUser apiUser = (ApiUser) clazz.getAnnotation(ApiUser.class);
        if(apiUser == null){
            return true;
        }
        Set<String> users = new HashSet<>();
        for(String u: StringUtils.split(apiUser.value(), ",")){
            if(StringUtils.isNotEmpty(u)){
                users.add(u);
            }
        }
        String curr = Scope.Session.current().get(ApiDoc.SessionKey_login);
        return users.contains(curr);
    }

    public static List<Class> getPermApiList(List<Class> classes){
        List<Class> list = new ArrayList();
        for(Class c: classes){
            if(hasPermission(c)){
                list.add(c);
            }
        }
        Collections.sort(list, new Comparator<Class>() {
            @Override
            public int compare(Class o1, Class o2) {
                ApiService a1 = (ApiService) o1.getAnnotation(ApiService.class);
                ApiService a2 = (ApiService) o2.getAnnotation(ApiService.class);
                if(a1.weight() == a2.weight()){
                    return 0;
                }
                return a1.weight() > a2.weight() ? -1 : 1;
            }
        });
        return list;
    }
}
